package repository

import (
	"context"
	"gitlab.com/gitlab-org/gitaly/v14/client"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git/catfile"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git/repository"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/rubyserver"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/transaction"
	"gitlab.com/gitlab-org/gitaly/v14/internal/storage"
	"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
)

type server struct {
	gitalypb.UnimplementedRepositoryServiceServer
	ruby              *rubyserver.Server
	conns             *client.Pool
	locator           storage.Locator
	txManager         transaction.Manager
	gitCmdFactory     git.CommandFactory
	cfg               config.Cfg
	binDir            string
	loggingCfg        config.Logging
	catfileCache      catfile.Cache
	archiveHousekeeping interface{ CheckExpiredRefs(context.Context, repository.GitRepo) error } // Optional archive housekeeping integration
}

// NewServer creates a new instance of a gRPC repo server
func NewServer(
	cfg config.Cfg,
	rs *rubyserver.Server,
	locator storage.Locator,
	txManager transaction.Manager,
	gitCmdFactory git.CommandFactory,
	catfileCache catfile.Cache,
) gitalypb.RepositoryServiceServer {
	return NewServerWithArchive(cfg, rs, locator, txManager, gitCmdFactory, catfileCache, nil)
}

// NewServerWithArchive creates a new instance of a gRPC repo server with optional archive housekeeping integration
func NewServerWithArchive(
	cfg config.Cfg,
	rs *rubyserver.Server,
	locator storage.Locator,
	txManager transaction.Manager,
	gitCmdFactory git.CommandFactory,
	catfileCache catfile.Cache,
	archiveHousekeeping interface{ CheckExpiredRefs(context.Context, repository.GitRepo) error },
) gitalypb.RepositoryServiceServer {
	return &server{
		ruby:                rs,
		locator:             locator,
		txManager:           txManager,
		gitCmdFactory:       gitCmdFactory,
		conns: client.NewPoolWithOptions(
			client.WithDialer(client.HealthCheckDialer(client.DialContext)),
			client.WithDialOptions(client.FailOnNonTempDialError()...),
		),
		cfg:                 cfg,
		binDir:              cfg.BinDir,
		loggingCfg:          cfg.Logging,
		catfileCache:        catfileCache,
		archiveHousekeeping: archiveHousekeeping,
	}
}

func (s *server) localrepo(repo repository.GitRepo) *localrepo.Repo {
	return localrepo.New(s.gitCmdFactory, s.catfileCache, repo, s.cfg)
}
